import time
import network
from umqttsimple import MQTTClient
import machine
import dht # DHT11的库

def do_connect():
    """
    作用：连接WiFi网络
    """
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        # 网络未连接
        wlan.connect('V40','123qiu456')
        i = 1
        while not wlan.isconnected():
            print(f"正在连接wifi...{i}s")
            time.sleep(1)
            i+=1
    print('已连接上网络，IP为:',wlan.ifconfig()[0])
    
def get_temp_hum():
    d.measure() # 触发传感器进行一次测量
    temp = d.temperature() # 获取温度 
    data = f"{temp}"
    return data


# 1. 联网
do_connect()

# 初始化DHT11信号引脚
d = dht.DHT11(machine.Pin(15)) 

# 2.创建mqtt
client = MQTTClient("esp32mqtt_DHT11","192.168.92.220")
client.connect() # 建立连接

while True:
    client.connect()
    data = get_temp_hum()
    client.publish(b"mqtt_esp32_project_DHT11",data)
    print("数据已发送：",data)
    time.sleep(3)
        

